home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 9590 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: rain.fr!world-net!usenet
  2. From: Frederic LACHASSE <lachass@worldnet.fr>
  3. Newsgroups: comp.lang.c++,rb.technical
  4. Subject: Re: Can copy constructor and operator= share code?
  5. Date: Sat, 02 Mar 1996 23:18:20 +0000
  6. Organization: World-Net information exchange, Internet provider.
  7. Message-ID: <VA.00000053.00cdab05@fred>
  8. References: <4h2kcn$40d@rap.SanDiegoCA.ATTGIS.COM>
  9. Reply-To: lachass@worldnet.fr
  10. NNTP-Posting-Host: pm9-025.sct.fr
  11. X-Newsreader: Virtual Access by Ashmount Research Ltd, http://www.ashmount.com
  12.  
  13. In article <4h2kcn$40d@rap.SanDiegoCA.ATTGIS.COM>, borisb@sd.znet.com 
  14. (Boris Burtin) wrote:
  15. > I have noticed that a copy constructor and operator= perform pretty
  16. > much the same function.  The code I wrote for my class simply copies
  17. > each member variable from one class to the other.
  18. > Is there a way for the one of the two functions to call the other, to
  19. > avoid duplicate code?  I have tried calling the copy constructor from
  20. > operator=, but nothing happens.  I've gotten around this problem by
  21. > creating a private Copy() function, which is called by both the copy
  22. > constructor and operator=.  Is there another way?
  23.  
  24. Generally, the operator=() must release old resource and create a copy 
  25. of the other object. So a generic operator=() can be:
  26.  
  27. T &T::operator =(const T &t)
  28. {
  29.   if (this != &t) // if objects are same, nothing to do
  30.   {
  31.     ~T(); // explicit call to destructor to release resources.
  32.     new(this) T(t); // use of the placement operator to call the
  33.                     // copy constructor.
  34.   }
  35. }
  36.  
  37. Some times though, the assignement operator can be optimize to reuse 
  38. resources of the old object.
  39.  
  40.  Frederic LACHASSE (ECP 86)
  41.  CompuServe: 100530,2005
  42.  Internet: lachass@worldnet.fr
  43.  
  44.